package com.webull.information.center.carwler.common.util;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.webull.framework.mvc.ApiException;
import com.webull.information.center.carwler.common.model.CarwlerJobConfig;
import com.webull.information.center.carwler.dao.CarwlerJobConfigDao;

/**
 * 当前carwler所在的身份信息
 */
@Component
public class CarwlerJobStateUtil {
    protected final Logger logger = LogManager.getLogger(getClass());
    /**
     * 爬取程序标记位
     */
    private @Value("${news.job.run:}")
    String carwler;

    private @Autowired
    CarwlerJobConfigDao carwlerJobConfigDao;

	public String getCarwler() {
		return carwler;
	}

	/**
	 * 是否base
	 *
	 * @return
	 */
    public boolean isCarwlerBase() {
        return carwlerJobConfig != null && carwlerJobConfig.isBase();
    }

    /**
     * wli_us_news_base_rel
     *
     * @return
     */
    public String getBaseRelTable() {
        assertCarwlerJobConfig(false);
        return carwlerJobConfig.getBaseRelTable();
    }


    public String getEdenNewsTable() {
        assertCarwlerJobConfig(false);
        return carwlerJobConfig.getEdenNewsTable();
    }


    public Integer getPastNewsIdByCarwler() {
        assertCarwlerJobConfig(false);
        return carwlerJobConfigDao.getPastNewsIdByCarwler(carwler);
    }

    public Integer getPastBaRelIdByCarwler() {
        assertCarwlerJobConfig(false);
        return carwlerJobConfigDao.getPastBaRelIdByCarwler(carwler);
    }


    @PostConstruct
    public void init() {
        logger.info("InfoSystemConfig init news_job_run:{}", carwler);
        if (StringUtils.isBlank(carwler)) return;
        carwlerJobConfig = carwlerJobConfigDao.searchByCarwler(carwler);
    }

    /**
     * assert config
     *
     * @param isMain
     */
    public void assertCarwlerJobConfig(boolean isMain) {
        if (carwlerJobConfig == null || isMain != carwlerJobConfig.isBase())
            throw new ApiException("carwlerJobConfig :" + carwlerJobConfig + ",isMain:" + isMain);
    }

    private CarwlerJobConfig carwlerJobConfig;


}
